package com.fl.nj.service.impl;

import com.fl.nj.entity.Area;
import com.fl.nj.mapper.AreaMapper;
import com.fl.nj.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 区域Service实现类
 * 实现区域的业务逻辑
 */
@Service
public class AreaServiceImpl implements AreaService {
    @Autowired
    private AreaMapper areaMapper;

    @Override
    @Transactional
    public void save(Area area) {
        // 验证区域名称是否已存在
        Area existingArea = areaMapper.getByAreaName(area.getAreaName());
        if (existingArea != null) {
            throw new RuntimeException("区域名称已存在: " + area.getAreaName());
        }
        
        // 验证必填字段
        validateArea(area);
        
        // 保存区域
        areaMapper.save(area);
    }

    @Override
    @Transactional
    public void update(Area area) {
        // 验证区域是否存在
        Area existingArea = areaMapper.getById(area.getId());
        if (existingArea == null) {
            throw new RuntimeException("区域不存在");
        }
        
        // 验证区域名称是否已被其他区域使用
        Area areaWithSameName = areaMapper.getByAreaName(area.getAreaName());
        if (areaWithSameName != null && !areaWithSameName.getId().equals(area.getId())) {
            throw new RuntimeException("区域名称已存在: " + area.getAreaName());
        }
        
        // 验证必填字段
        validateArea(area);
        
        // 更新区域
        areaMapper.update(area);
    }

    @Override
    public Area getById(Long id) {
        return areaMapper.getById(id);
    }

    @Override
    public Area getByAreaName(String areaName) {
        return areaMapper.getByAreaName(areaName);
    }

    @Override
    public List<Area> getAll() {
        return areaMapper.getAll();
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 验证区域是否存在
        Area area = areaMapper.getById(id);
        if (area == null) {
            throw new RuntimeException("区域不存在");
        }
        
        // 验证区域下是否有设备
        int deviceCount = areaMapper.countDevices(id);
        if (deviceCount > 0) {
            throw new RuntimeException("该区域下有设备，无法删除");
        }
        
        // 删除区域
        areaMapper.delete(id);
    }

    @Override
    public int countDevices(Long areaId) {
        return areaMapper.countDevices(areaId);
    }

    /**
     * 验证区域的必填字段
     * @param area 区域对象
     */
    private void validateArea(Area area) {
        if (area.getAreaName() == null || area.getAreaName().trim().isEmpty()) {
            throw new RuntimeException("区域名称不能为空");
        }
    }
}